<?php

namespace App\Http\Controllers\Admin;

use App\Helpers\Pinyin;
use App\Models\Item;
use App\Models\ItemCatlog;
use App\Models\ItemCatlogProps;

class ItemCatlogController extends BaseController
{
    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(){

        if ($this->isOnSubmit()) {
            $catloglist = $this->request->post('catloglist');
            if (is_array($catloglist)){
                $pinyin = new Pinyin();
                foreach ($catloglist as $catid=>$catlog){
                    if ($catlog['name']) {
                        if (!$catlog['identifier']) {
                            $catlog['identifier'] = $pinyin->getPinyin($catlog['name']);
                        }
                        $catlog['enable'] = intval($catlog['enable']);
                        $catlog['displayorder'] = intval($catlog['displayorder']);
                        ItemCatlog::where('catid', $catid)->update($catlog);
                    }
                }
                ItemCatlog::updateCache();
            }
            return $this->messager()->message(trans('sysmessage.info update success'))->render();
        }else {

            return $this->view('admin.itemcatlog.catlog', [
                'catloglist'=>$this->getCatlogs()
            ]);
        }
    }

    /**
     * 编辑分类
     */
    public function newcatlog(){

        $catid = $this->request->get('catid');
        if ($this->isOnSubmit()){
            $catlog = $this->request->post('catlog');
            if ($catlog['name']) {
                $pinyin = new Pinyin();
                $catlog['identifier'] = $pinyin->getPinyin($catlog['name']);
                if ($catid) {
                    ItemCatlog::where('catid', $catid)->update($catlog);
                }else {
                    ItemCatlog::insert($catlog);
                }
                ItemCatlog::updateCache();
                return $this->messager()->message(trans('sysmessage.info update success'))
                    ->links([
                        [trans('sysmessage.reedit'), url()->current()],
                        [trans('sysmessage.back_list'), admin_url('itemcatlog')]
                    ])->render();
            }else {
                return $this->messager()->error()->message(trans('sysmessage.invalid parameter'))->render();
            }
        }else {

            $this->assign([
                'catid'=>$catid,
                'catlog'=>[
                    'fid'=>0,
                    'name'=>'',
                    'typeid'=>0,
                    'enable'=>1,
                    'available'=>1,
                    'template_index'=>'',
                    'template_list'=>'',
                    'template_detail'=>'',
                    'keywords'=>'',
                    'description'=>''
                ] ,
                'catloglist'=>$this->getCatlogs(),
            ]);

            if ($catid) {
                $catlog = ItemCatlog::find($catid);
                if ($catlog) $this->assign(['catlog'=>$catlog]);
            }

            return $this->view('admin.itemcatlog.newcatlog');
        }
    }

    /**
     * 删除分类
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Exception
     */
    public function delete(){

        $catid = $this->request->input('catid');
        if ($this->isOnSubmit()){
            $moveto = intval($this->request->get('moveto'));
            $deleteChilds = intval($this->request->get('deleteChilds'));

            if (!$deleteChilds && !$moveto){
                return $this->messager()->error()->message(trans('sysmessage.invalid parameter'))->render();
            }

            if ($deleteChilds) {
                $Ids = ItemCatlog::fetchAllChildIds($catid);
                Item::whereIn('catid', $Ids)->get()->map(function (Item $item){
                    $item->delete();
                });
                ItemCatlog::whereIn('catid', $Ids)->delete();
                ItemCatlogProps::whereIn('catid', $Ids)->delete();
            }else {
                ItemCatlog::where('fid', $catid)->update(['fid'=>$moveto]);
                Item::where('catid', $catid)->update(['catid'=>$moveto]);
                ItemCatlog::where('catid', $catid)->delete();
                ItemCatlogProps::where('catid', $catid)->delete();
            }

            ItemCatlog::updateCache();
            return $this->messager()->links([
                [trans('sysmessage.back_list'), admin_url('itemcatlog')]
            ])->render();
        }else {

            $this->assign([
                'catid'=>$catid,
                'catlog'=>ItemCatlog::find($catid),
                'catlogOptions'=>ItemCatlog::getOptions()
            ]);

            return $this->view('admin.itemcatlog.delete');
        }
    }

    /**
     * 合并分类
     * @throws \Exception
     */
    public function merge(){

        if ($this->isOnSubmit()){
            $target = $this->request->post('target');
            $source = $this->request->post('source');
            if ($source && $target && $source != $target) {
                foreach ($source as $catid){
                    if ($catid != $target){
                        Item::where('catid', $catid)->update(['catid'=>$target]);
                        ItemCatlog::where('catid', $catid)->delete();
                        ItemCatlogProps::where('catid', $catid)->delete();
                    }
                }
            }
            return $this->messager()->render();
        }else {

            return $this->view('admin.itemcatlog.merge', [
                'catlogOptions'=>ItemCatlog::getOptions()
            ]);
        }
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Exception
     */
    public function props()
    {
        $catid = $this->request->input('catid');
        if ($this->isOnSubmit()) {
            $delete = $this->request->input('delete');
            if ($delete) {
                foreach ($delete as $prop_id) {
                    ItemCatlogProps::where('prop_id', $prop_id)->delete();
                }
            }
            return $this->messager()->message(trans('sysmessage.info delete success'))->render();
        } else {

            $properties = ItemCatlogProps::where('catid', $catid)->get();
            $this->assign([
                'catid'=>$catid,
                'properties'=>$properties,
                'prop_types'=>trans('mall.prop_types')
            ]);

            return $this->view('admin.itemcatlog.props');
        }
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function newProps()
    {
        $catid = $this->request->input('catid');
        $prop_id = $this->request->input('prop_id');

        if ($this->isOnSubmit()) {
            $prop = $this->request->input('prop');
            if ($prop['title']) {
                $prop['catid'] = $catid;
                if ($prop_id) {
                    ItemCatlogProps::where('prop_id', $prop_id)->update($prop);
                    return $this->messager()->message(trans('sysmessage.info update success'))->render();
                } else {
                    ItemCatlogProps::insert($prop);
                }
            }
            return $this->messager()->render();
        } else {
            $this->assign([
                'catid'=>$catid,
                'prop'=>[
                    'title'=>'',
                    'type'=>'',
                    'default'=>'',
                    'required'=>0,
                    'options'=>'',
                    'rules'=>''
                ],
                'prop_id'=>$prop_id
            ]);

            if ($prop_id) {
                $prop = ItemCatlogProps::find($prop_id);
                $this->assign(['prop'=>$prop]);
            }


            return $this->view('admin.itemcatlog.newprops');
        }
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function extendProps()
    {
        $catid = $this->request->input('catid');
        $catlog = ItemCatlog::find($catid);
        if ($catlog->fid) {
            ItemCatlogProps::where('catid', $catlog->fid)->get()->map(function ($prop) use($catid){
                $newProps = $prop->toArray();
                $newProps['catid'] = $catid;
                unset($newProps['prop_id']);
                ItemCatlogProps::insert($newProps);
            });
        }
        return ajaxReturn();
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function setIcon(){
        $catid = $this->request->input('catid');
        $icon  = $this->request->input('icon');
        if ($catid && $icon){
            ItemCatlog::where('catid', $catid)->update(['icon'=>$icon]);
            ItemCatlog::updateCache();
        }
        return ajaxReturn();
    }

    /**
     * @return array|mixed
     */
    private function getCatlogs()
    {
        $catloglist = [];
        ItemCatlog::with('childs')->orderBy('displayorder')->get()->map(function ($catlog) use (&$catloglist){
            $catloglist[$catlog->fid][$catlog->catid] = $catlog;
        });

        if ($catloglist) {
            return $catloglist[0];
        } else {
            return [];
        }
    }
}
